import { computed, ref, Ref } from 'vue';
import type { TableProps, TableEmits, Cell, ValidationError, Column } from '../type';
import { ElMessage, ElMessageBox } from 'element-plus';

export function editModule(props: TableProps, data: Ref<Cell[]>, emit: TableEmits) {  // 编辑状态管理
  const editingRowIndex = ref<number | null>(null);
  const editingData = ref<Record<number, Record<string, any>>>({});
  const originalRowData = ref<Record<string, any> | null>(null);

  // 验证错误状态管理
  const validationErrors = ref<ValidationError>({});

  // 字段验证函数
  const validateField = (rowIndex: number, field: string): string => {
    // 只使用 props.validationRules，不再使用 columnRules 参数
    const validationRules = props.validationRules && props.validationRules[field];
    if (!validationRules || !editingData.value[rowIndex]) return '';

    const value = editingData.value[rowIndex][field];

    for (const rule of validationRules) {
      // 必填验证
      if (rule.required && (value === undefined || value === null || value === '')) {
        return rule.message || `${field} 为必填项`;
      }

      // 正则表达式验证
      if (rule.pattern && value !== undefined && value !== null && value !== '') {
        if (!rule.pattern.test(String(value))) {
          return rule.message || `${field} 格式不正确`;
        }
      }

      // 自定义验证器
      if (rule.validator && !rule.validator(value)) {
        return rule.message || `${field} 不符合要求`;
      }
    }

    return '';
  };
  // 行数据验证函数
  const validateRowData = (rowIndex: number): boolean => {
    const errors: Record<string, string> = {};
    let isValid = true;

    props.columns.forEach((column: Column) => {
      // 只验证有component的列
      if (column.component && editingData.value[rowIndex]?.[column.prop] !== undefined) {
        const error = validateField(rowIndex, column.prop);
        if (error) {
          errors[column.prop] = error;
          isValid = false;
        }
      }
    });

    // 更新验证错误状态
    if (Object.keys(errors).length > 0) {
      validationErrors.value[rowIndex] = errors;
    } else {
      delete validationErrors.value[rowIndex];
    }

    return isValid;
  };

  // 保存行编辑
  const saveRowEdit = (rowIndex: number) => {
    // 数据验证（保持不变，因为 validateRowData 内部已修改）
    if (!validateRowData(rowIndex)) {
      ElMessage.error('数据验证失败，请检查输入内容');
      return;
    }
    // 验证通过，更新数据
    const newData = [...data.value];
    newData[rowIndex] = { ...newData[rowIndex], ...editingData.value[rowIndex] };
    // 清除验证错误
    delete validationErrors.value[rowIndex];
    // 触发行编辑事件
    emit('row-edit', rowIndex, newData[rowIndex]);
  };

  // 取消行编辑
  const cancelRowEdit = (rowIndex: number) => {
    // 获取要取消编辑的行数据
    const rowData = data.value[rowIndex];

    // 判断是否为新增数据（无id或id为临时值）
    const isNewRow = !rowData.id || (typeof rowData.id === 'number' && rowData.id > 999999999999);
    if (isNewRow) {
      // 如果是新增数据，直接删除该行
      const newData = [...data.value];
      newData.splice(rowIndex, 1);
      data.value = newData;
      // 清空编辑状态
      editingRowIndex.value = null;
      originalRowData.value = null;

      // 清空该行的编辑数据和验证错误
      delete editingData.value[rowIndex];
      delete validationErrors.value[rowIndex];
    } else {
      // 如果是已保存数据，恢复原始数据
      if (originalRowData.value) {
        const newData = [...data.value];
        newData[rowIndex] = { ...originalRowData.value };
        data.value = newData;
      }
      // 清空编辑状态
      editingRowIndex.value = null;
      originalRowData.value = null;

      // 清空该行的编辑数据和验证错误
      delete editingData.value[rowIndex];
      delete validationErrors.value[rowIndex];
    }
  };

  // 删除行
  const deleteRow = (rowIndex: number) => {
    if (editingRowIndex.value !== null) {
      ElMessage.warning('请先保存或取消当前正在编辑的行数据');
      return;
    }
    // 已保存数据需要确认
    ElMessageBox.confirm('确定要删除这一行数据吗？', '删除确认', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    })
      .then(() => {
        emit('row-delete', rowIndex);
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
  };

  // 开始行编辑
  const startRowEdit = (rowIndex: number) => {
    // 检查是否已有正在编辑的行
    if (editingRowIndex.value !== null && editingRowIndex.value !== rowIndex) {
      ElMessage.warning('请先保存或取消当前正在编辑的行数据');
      return;
    }
    // 设置当前行进入编辑状态
    editingRowIndex.value = rowIndex;
    originalRowData.value = { ...data.value[rowIndex] };

    // 初始化整行的编辑数据
    if (!editingData.value[rowIndex]) {
      editingData.value[rowIndex] = {};
    }

    // 复制当前行的所有数据到编辑数据中，只处理有component的列
    props.columns.forEach((column: Column) => {
      if (column.component) {
        editingData.value[rowIndex][column.prop] = data.value[rowIndex][column.prop];
      }
    });
  };

  // 检查是否正在编辑
  const isEditing = () => editingRowIndex.value !== null;
  const isEditingRef = computed(() => editingRowIndex.value !== null);
  const closeEditingState = () => {
    // 清空编辑状态
    editingRowIndex.value = null;
    originalRowData.value = null;
  };
  return {
    // 状态
    editingRowIndex,
    editingData,
    originalRowData,
    validationErrors,
    isEditingRef, // 添加这个
    isEditing,

    // 方法
    startRowEdit,
    saveRowEdit,
    cancelRowEdit,
    deleteRow,
    validateField,
    validateRowData,
    closeEditingState
  };
}
